package com.bdqn.t382.filter;

import com.alibaba.fastjson2.util.DateUtils;
import org.springframework.core.convert.converter.Converter;

import java.util.Date;

public class String2DateConverter  implements Converter<String, Date> {
    //dataFormats 数组默认值
    public String[] dataFormats = {"yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm"};

    //通过spring去注入
    public void setDataFormats(String[] dataFormats) {
        this.dataFormats = dataFormats;
    }

    @Override
    public Date convert(String source) {
        for (int i = 0; i < dataFormats.length; i++) {
            try {
                return DateUtils.parseDate(source, dataFormats[i]);
            } catch (Exception e) {

            }
        }
        throw new RuntimeException("日期格式转换异常");
    }
}
